package com.by.auth.reamls;

import com.by.auth.LoginType;
import com.by.auth.MyUsernamePasswordToken;
import com.by.auth.UserInfo;

import java.util.UUID;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自定义的shirorealm实现类
 *
 * @author hsitung
 */
@SuppressWarnings("all")
public class MyShiroJdbcRealmAdmin extends AuthorizingRealm {
	
	private Logger log = LoggerFactory.getLogger(MyShiroJdbcRealmAdmin.class);
	
	
    /**
     * 返回字符串
     * @return
     */
    @Override
    public String getName() {
    	return LoginType.ADMIN.toString();
        //return this.getClass().getName();
    }

    /**
     * 支持的token类型
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof MyUsernamePasswordToken;
    }

    /**
     * 授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    	
    	//校验当前用户类型是否正确，正确则进入处理角色权限问题，否则跳出
        if (!principals.getRealmNames().contains(getName())) {
        	return null;
        }
    	
        log.debug("ADMIN管理授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        info.addRole("ROLE_ADMIN");

//        Set<String> permissions = new HashSet<String>();
//        permissions.add("*");
//        info.setStringPermissions(permissions);

        return info;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected SimpleAuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.debug("ADMIN管理认证");
	    UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        if (!"admin".equals(token.getUsername())) {
            throw new AuthenticationException("登录账号或密码不匹配");
        }
        
        UserInfo userInfo = new UserInfo(UUID.randomUUID().toString(), token.getUsername());
        
	    return new SimpleAuthenticationInfo(userInfo, token.getPassword(), getName());
    }
}
